import { Tray, Menu, BrowserWindow, app } from "electron";
import { join } from "node:path";
import { existsSync } from "node:fs";

class TrayManager {
  private tray: Tray | null = null;
  private win: BrowserWindow | null = null;
  private cachedTrayIconPath: string | null = null;
  private isDev: boolean;

  constructor(win: BrowserWindow | null, isDev: boolean) {
    this.win = win;
    this.isDev = isDev;
  }

  // 设置主窗口引用
  setMainWindow(win: BrowserWindow) {
    this.win = win;
  }

  // 获取托盘图标路径
// ... existing code ...
  // 获取托盘图标路径
  private getTrayIconPath(): string {
    if (this.cachedTrayIconPath) {
      return this.cachedTrayIconPath;
    }

    const getIconFileName = () => {
      if (process.platform === "darwin") {
        // 首先检查是否有 macOS 专用的模板图标
        const templateIconPath = join(process.env.PUBLIC!, "tray-iconTemplate.png");
        if (existsSync(templateIconPath)) {
          return "tray-iconTemplate.png";
        }
        // 如果没有，则使用普通图标
        return "tray-icon-16x16.png";
      }
      return "tray-icon-16x16.png";
    };

    const possiblePaths = [
      this.isDev
        ? join(process.env.DIST_ELECTRON!, "../public", getIconFileName())
        : null,
      join(process.env.PUBLIC!, getIconFileName()),
      join(process.env.DIST!, getIconFileName()),
      join(process.resourcesPath, getIconFileName()),
      // 调整 favicon.ico 的优先级，放在 PNG 格式图标之后
      join(process.env.PUBLIC!, "favicon.ico"),
      process.platform === "win32"
        ? join(process.resourcesPath, "app.ico")
        : join(process.resourcesPath, "app.png")
    ].filter(Boolean) as string[];

    for (const path of possiblePaths) {
      try {
        if (existsSync(path)) {
          console.log(`found tray icon at path: ${path}`);
          this.cachedTrayIconPath = path;
          return this.cachedTrayIconPath;
        }
      } catch (error) {
        console.warn(`failed to check if file exists at path: ${path}`, error);
        continue;
      }
    }

    console.warn("tray icon not found, using default icon");
    this.cachedTrayIconPath = "";
    return this.cachedTrayIconPath;
  }
// ... existing code ...

// ... existing code ...
  // 创建系统托盘
  createTray() {
    const trayIconPath = this.getTrayIconPath();

    try {
      // 在 macOS 上添加额外的参数检查
      if (process.platform === "darwin" && (!trayIconPath || trayIconPath === "")) {
        console.warn("Skipping tray creation on macOS due to missing icon");
        return;
      }

      this.tray = new Tray(trayIconPath);

      this.tray.setToolTip("PureAdmin");

      const contextMenu = Menu.buildFromTemplate([
        {
          label: "显示主窗口",
          click: () => {
            if (this.win) {
              this.win.show();
              this.win.focus();
            }
          }
        },
        { type: "separator" },
        {
          label: "退出",
          click: () => {
            app.quit();
          }
        }
      ]);

      this.tray.setContextMenu(contextMenu);

      if (process.platform === "darwin") {
        this.tray.on("click", () => {
          if (this.win) {
            this.win.isVisible() ? this.win.hide() : this.win.show();
          }
        });
      } else {
        this.tray.on("click", () => {
          if (this.win) {
            this.win.show();
            this.win.focus();
          }
        });
        this.tray.on("double-click", () => {
          if (this.win) {
            this.win.show();
            this.win.focus();
          }
        });
      }
    } catch (error) {
      console.error("makeTray error:", error);
      // 在 macOS 上忽略托盘创建错误，避免应用崩溃
      if (process.platform === "darwin") {
        console.warn("Tray creation failed on macOS, continuing without tray icon");
      }
    }
  }
// ... existing code ...

  // 销毁托盘
  destroy() {
    if (this.tray) {
      this.tray.destroy();
      this.tray = null;
    }
    this.cachedTrayIconPath = null;
  }
}

export default TrayManager;